package util.tool;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
 * 简单封装的httpGet，使用前务必提前new一下，以加载Http代理
 * @author kong
 *
 */
public class Requests {
	
//	public static void main(String[] args) {
//		Requests requests = new Requests();
//		try {
//			String url = "http://is.snssdk.com/api/2/wap/search_content/?from=search_tab&keyword=%E9%A3%9F%E5%93%81&iid=10344168417&device_id=36394312781&count=10&cur_tab=1&format=json&offset=20";
//			String reString = requests.myGet("http://127.0.0.1:5000/", new String[]{"x-requested-with:XMLHttpRequest"});
//			System.out.println(reString);
//			JsonParser jsonParser = new JsonParser();
//			JsonObject data = (JsonObject)jsonParser.parse(reString);
//			System.out.println(data.get("count").getAsInt());
//		} catch (Exception e) {
//			// TODO: handle exception
//			e.printStackTrace();
//			System.err.println(e.getMessage());
//		}
//	}
	ProxyPool pool = new ProxyPool();
	/**
	 * 使用http代理访问url
	 * @param url 访问的链接
	 * @param headers 访问所需的http headers
	 * @return 请求后返回的内容
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String proxyGet(String url, String[] headers) throws ClientProtocolException, IOException {
		while (pool.count == 0) // 线程池为空，强制休眠
			try {
				Thread.sleep(500); 
			} catch (Exception e) {
			}
		return myGet(url, headers, pool.getProxy());
	}
	/**
	 * 不使用header和代理，执行http的get请求
	 * @param url 访问的链接
	 * @return 访问所返回的数据
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	static public String myGet(String url) throws ClientProtocolException, IOException {
		return myGet(url, null, null);
	}
	/**
	 * 使用指定http代理和header，进行http的get请求
	 * @param url 访问的链接
	 * @param headers 所需的http的headers
	 * @param proxy 所用的代理地址
	 * @return 访问所返回的数据
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	static public String myGet(String url, String[] headers, String proxy) throws ClientProtocolException, IOException {
		HttpGet httpGet = new HttpGet(url);
		
		for (int i = 0; headers != null && i < headers.length; i++) {
			String[] tmp = headers[i].split(":");
			httpGet.addHeader(tmp[0], tmp[1]);
		}
		httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36");
		// 设置代理
		if (proxy != null) {
			RequestConfig requestConfig = RequestConfig.custom()
					.setProxy(new HttpHost(proxy.split(":")[0], Integer.valueOf(proxy.split(":")[1])))
					.setSocketTimeout(10000).setConnectTimeout(10000)
					.build();
			httpGet.setConfig(requestConfig);
		}
		HttpClient httpClient = HttpClients.createDefault();
		HttpResponse httpResponse = httpClient.execute(httpGet);
		HttpEntity httpEntity = httpResponse.getEntity();
		String returnString = null;
		try {
			returnString = EntityUtils.toString(httpEntity, "utf8");			
		} catch (Exception e) {
			returnString = EntityUtils.toString(httpEntity, "gbk");
		}
		return returnString;
	}
}
